package com.example.emojibase.view;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AlertDialog;

import androidx.appcompat.app.AppCompatActivity;

import com.example.emojibase.EmojiBaseDB;
import com.example.emojibase.R;
import com.example.emojibase.adapter.EmojiAdapter;
import com.example.emojibase.pojo.Emoji;
import com.example.emojibase.utils.CommonUtils;


public class EmojiDetail extends AppCompatActivity {

    private EmojiAdapter emojiAdapter;
    private Emoji emoji;
    private int position;
    private Context mcontext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.emoji_detail);
        mcontext=this;
        position=getIntent().getIntExtra("ITEM_POSITION", -1);
        ImageView img=findViewById(R.id.imageView);
        emojiAdapter=EmojiAdapter.getInstance(this);
        emoji=emojiAdapter.getEmojiByPosition(position);
        Bitmap imagebitmap = BitmapFactory.decodeByteArray(emoji.getAvatar(), 0, emoji.getAvatar().length);
        img.setImageBitmap(imagebitmap);
        Button deleteButton = findViewById(R.id.deleteButton);
        Button saveButton = findViewById(R.id.saveButton);
        deleteButton.setOnClickListener(view -> {
            showConfirmDialog();
            //删除确认
        });

        saveButton.setOnClickListener(view -> {
            CommonUtils.bitmapToFile(emoji.getAvatar(), this.getFilesDir().getPath() +"/png/", emoji.getName());
        });


    }

    private void showConfirmDialog() {
        // 创建AlertDialog.Builder实例
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 设置标题
        builder.setTitle("确认操作");
        // 设置消息
        builder.setMessage("你确定要执行这个操作吗？");
        // 设置“确定”按钮
        builder.setPositiveButton("确定", (dialog, which) -> {
            // 用户点击“确定”按钮时的操作
            String emojiId=String.valueOf(emoji.getId());
            EmojiBaseDB emojiBaseDB=EmojiBaseDB.getInstance(mcontext);
            SQLiteDatabase db = emojiBaseDB.getWritableDatabase();
            db.delete("Emoji", "emoji_id=?",new String[]{emojiId});
            emojiAdapter.removeEmojiByPosition(position);
            dialog.dismiss();
            finish();
            // 执行相关操作，例如删除数据、退出应用等
        });
        // 设置“取消”按钮
        builder.setNegativeButton("取消", (dialog, which) -> {
            // 用户点击“取消”按钮时的操作
            dialog.cancel();
        });
        // 创建AlertDialog
        AlertDialog alertDialog = builder.create();
        // 显示AlertDialog
        alertDialog.show();
    }

}
